﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Xml;
using SEAM.Exception.Formatter;

namespace SEAM.Exception.Publisher
{
    public class EventLogPublisher : ExceptionPublisherBase
    {
        private string _logSource;
        private string _logName;

        public string LogSource
        {
            get { return _logSource; }
            set { _logSource = value; }
        }
        public string LogName
        {
            get { return _logName; }
            set { _logName = value; }
        }

        public EventLogPublisher(XmlNode node) 
            : base(node) 
        {
            LogSource = GetAttributeValue(node, "LogSource", true);
            LogName = GetAttributeValue(node, "LogName", true);

            if (!EventLog.SourceExists(LogSource))
                EventLog.CreateEventSource(LogSource, LogName);

        }

        public override bool PublishException(System.Exception ex, IDictionary<string, object> additionalInfo)
        {
            try
            {
                EventLog evtLog = new EventLog();
                evtLog.Source = LogSource;
                evtLog.WriteEntry(GetFormattedMessage(ex, Format, additionalInfo), EventLogEntryType.Error);
            }
            catch (System.Exception ex2)
            {
                Trace.TraceWarning(ex2.Message + Environment.NewLine + ex2.StackTrace);
                return false;
            }
            return true;
        }
    }
}
